<template>
  <div class="app-container">

    <el-card class="box-card">
      <h4>{{ $t("Basic_Information") }}</h4>
      <el-form
        ref="packageForm"
        :rules="rules"
        :model="packageForm"
        label-width="150px"
      >
        <el-form-item
          :label="$t('选择区域')"
          prop="regionId"
        >
          <el-button type="primary" size="mini" @click="addRegion">{{
            $t("添加区域")
          }}</el-button>
          <p v-for="(item, i) in regions">
            <el-select
              v-model="regions[i].countryId"
              filterable
              @change="(value) => changeCountry(i, value)"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="country in regionList[i].countrys"
                :label="country.nameCn || country.nameEn"
                :value="country.id"
              >
              </el-option>
            </el-select>

            <el-select
              v-model="regions[i].provinceId"
              filterable
              @change="(value) => changeProvince(i, value)"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="province in regionList[i].provinces"
                :key="province.id"
                :label="province.nameCn || province.nameEn"
                :value="province.id"
              >
              </el-option>
            </el-select>

            <el-select
              v-model="regions[i].cityId"
              filterable
              @change="(value) => changeCity(i, regions[i], value)"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="city in regionList[i].citys"
                :key="city.id"
                :label="city.nameCn || city.nameEn"
                :value="city.id"
              >
              </el-option>
            </el-select>

            <el-button type="danger" size="mini" @click="deleteRegion(i)">{{
              $t("Delete")
            }}</el-button>

            <el-row>
              <el-col :span="2">{{ $t("税率类型") }}：</el-col>
              <el-col :span="22">
                <el-checkbox-group v-model="regions[i].taxTypes">
                  <el-checkbox
                    v-for="tax in regionList[i].taxTypes"
                    :label="tax.id"
                    :key="tax.id"
                    >{{ tax.code }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </p>
        </el-form-item>


        <el-form-item :label="$t('Category')">
          <el-cascader :style="{width: '100%'}" :options="categoryList" v-model="packageForm.categoryIds" expand-trigger="hover" @change="handleCategoryChange" :placeholder="$t('请选择')"/>
        </el-form-item>
        <el-form-item :label="$t('套餐编号')" prop="packageNumber">
          <el-input  v-model="packageForm.lumierePackage.packageNumber"/>
        </el-form-item>
        <el-form-item :label="$t('套餐名称')" prop="packageName">
          <el-input v-model="packageForm.lumierePackage.packageName"/>
        </el-form-item>
<!--        <el-form-item :label="$t('缩写')" prop="subhead">
          <el-input v-model="packageForm.lumierePackage.subhead"/>
        </el-form-item>-->
        <el-form-item :label="$t('金额')" prop="subhead">
          <el-input-number v-model="packageForm.lumierePackage.amount" :precision="2" :step="0.1" >
            <span slot="prefix">$</span>
          </el-input-number>
        </el-form-item>
        <!-- <el-form-item :label="$t('计量单位')" prop="unit">
          <el-input v-model="packageForm.unit"/>
        </el-form-item> -->
        <el-form-item :label="$t('套餐简介')">
          <el-input v-model="packageForm.lumierePackage.packageIntroduction"/>
        </el-form-item>
        <el-form-item :label="$t('套餐图片')">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            :on-remove="handleGoodsPicRemove"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="packageForm.lumierePackage.packageImg" :src="packageForm.lumierePackage.packageImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
            <label v-if="packageForm.lumierePackage.packageImg" class="el-upload-list__item-status-label avatar-uploader__status_label" @click.stop="handleGoodsPicRemove()"><i class="el-icon-delete"></i></label>
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('Gallery')">
          <el-upload
              :class="{hide:hideUpload}"

              :action="uploadPath"
            :headers="headers"
            :limit="5"
            :file-list="galleryFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            :multiple="false"
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('套餐详情介绍')">
          <el-input type="textarea" :init="editorInit" v-model="packageForm.lumierePackage.packageDetailsIntroduce"/>
        </el-form-item>
<!--        <el-form-item :label="$t('操作说明')">
          <el-input type="textarea" v-model="packageForm.lumierePackage.operationExplain"></el-input>
        </el-form-item>-->
        <el-form-item :label="$t('Goods_tax_type')" v-if="shop">
          <el-checkbox-group v-model="regions[0].taxTypes">
            <el-checkbox
              v-for="tax in shopTaxTypes"
              :label="tax.id"
              :key="tax.id"
              >{{ tax.code }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('套餐营业时间')">
          <el-popover
            @show="handleShow"
            placement="right"
            trigger="click">
            <el-descriptions class="margin-top" :title="$t('说明：如不营业请设置服务时间为 00:00:00-00:00:00')" :column="2" border>
              <el-descriptions-item v-for="o in 7" :span="1">
                <template slot="label">
                  <el-tag :style="{width:'80px','text-align':'center'}" type="info">{{weeksTimeMap[o] }}</el-tag>
                </template>
                <el-time-picker
                  format="HH:mm:ss" value-format="HH:mm:ss"
                  is-range
                  :clearable="false"
                  v-model="weeksTime[o-1]"
                  range-separator="-"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')"
                  :placeholder="$t('选择时间')">
                </el-time-picker>
              </el-descriptions-item>
              <template slot="extra">
                <el-button type="primary" size="small" @click="showDatePicker"> {{!showDatepicker?$t('添加特殊日期'):$t('关闭') }}</el-button>
                <el-date-picker
                  :clearable="false"
                  value-format="yyyy-MM-dd"
                  @change="handleChangePicker"
                  v-model="selectedDate"
                  v-if="showDatepicker" >
                </el-date-picker>
              </template>
              <!--              特殊日期-->
              <el-descriptions-item  v-for="o in this.special.length" :span="1">
                <template slot="label">
                  <el-tag effect="dark" type="warning">{{special[o-1].specialDate }}</el-tag>
                </template>
                <el-time-picker
                  format="HH:mm:ss" value-format="HH:mm:ss"
                  is-range
                  :clearable="false"
                  v-model="special[o-1].specialTime"
                  range-separator="-"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')"
                  :placeholder="$t('选择时间')">
                </el-time-picker>
                <el-button :style="{'margin-left':'5px'}" @click="handleSpecialTimeDeleted(o-1)" size="mini" type="danger" icon="el-icon-delete" ></el-button>
              </el-descriptions-item>
            </el-descriptions>
            <el-button type="text" icon="el-icon-setting" slot="reference">{{$t('设置营业时间')}}</el-button>
          </el-popover>
        </el-form-item>
      </el-form>
    </el-card>

    <!--套餐商品-->
    <el-card class="box-card">
      <h4>
        {{ $t("套餐商品") }}({{this.packageCategoryList.reduce((sum, category) => sum + category.quantity, 0)}})
        <el-tooltip class="item" effect="dark" content="此数量为套餐中的“类目个数”，类目指的是套餐商品的种类" placement="top-start">
          <i class="el-icon-info"></i>
        </el-tooltip>
      </h4>
      <el-tabs type="border-card" v-model="packageCategoryId" @tab-click="handleClickCategoryTabs">
        <el-tab-pane v-for="item in packageCategoryList" :key="item.id"  :name="item.id">
          <div slot="label"> {{item.categoryName }}
            <el-link>
              <i class="el-icon-edit" @click="handlerUpdatePackageCategory(item)"></i>
            </el-link>
            <el-link>
              <el-popconfirm
                @confirm="handlePackageCategoryRemove(item)"
                title="本类目下面的商品将全部删除，确定删除吗？">
                <i slot="reference" class="el-icon-delete"></i>
              </el-popconfirm>
            </el-link>
          </div>
          <el-button
            :plain1="true"
            type="primary"
            icon="el-icon-circle-plus"
            @click="handerPackageGoods"
          >{{ $t('添加套餐商品') }}</el-button>
          <el-empty v-if="packageCategoryList.length == 0" description="还没有内容～" :image-size="200"></el-empty>
          <!-- 查询结果 -->
          <el-table
            v-loading="listPackageGoodsLoading"
            :data="packageGoodsList"
            :element-loading-text="$t('Searching')"
          >

            <el-table-column
              type="index"
              width="100"
              :label="$t('序号')"
            />

            <el-table-column
              align="center"
              min-width="100"
              :label="$t('商品分类')"
              prop="categoryName"
            />

            <el-table-column
              align="center"
              min-width="100"
              :label="$t('商品名称')"
              prop="Goods">
              <template slot-scope="scope">
                {{scope.row.goods.name}}
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              min-width="100"
              :label="$t('商品图片')"
              prop="Goods">
              <template slot-scope="scope">
                <el-image
                  :style="{width: '100px', height: '100px' ,borderRadius: '5px'}"
                  :src="scope.row.goods.picUrl" fit="fill">
                </el-image>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              min-width="100"
              :label="$t('商品数量')"
              prop="quantity">
              <template slot-scope="scope">
                x{{scope.row.quantity}}
              </template>
            </el-table-column>

            <!--            <el-table-column
                            align="center"
                            min-width="100"
                            :label="$t('金额')"
                            prop="Goods">
                          <template slot-scope="scope">
                            {{scope.row.amount>=0?'+':''}}$ {{scope.row.amount}}
                          </template>
                        </el-table-column>-->


            <!--            <el-table-column
                            align="center"
                            min-width="100"
                            :label="$t('单位')"
                            prop="Goods">
                          <template slot-scope="scope">
                            {{scope.row.unit}}
                          </template>
                        </el-table-column>-->

            <el-table-column
              align="center"
              min-width="100"
              :label="$t('是否默认')"
              prop="Goods">
              <template slot-scope="scope">
                <span :style="{color:scope.row.isDefault?'#3a8ee6':''}">{{scope.row.isDefault?'是':'否'}}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              :label="$t('Operate')"
              width="200"
              class-name="small-padding fixed-width"
            >
              <template slot="header" slot-scope="{ row }">
                {{ $t("Operate") }}
                <i class="el-icon-setting" style="color: #d35e32"></i>
              </template>

              <template slot-scope="scope">
                <el-link
                  size="small"
                  type="primary"
                  @click="handlerEditPackageGoods(scope.row)"
                >
                  <i class="el-icon-edit">{{ $t("编辑") }}</i>
                </el-link>

                <el-link
                  size="small"
                  type="danger"
                  @click="handlerDeletePackageGoods(scope.row)"
                >
                  <i class="el-icon-delete">{{ $t("删除") }}</i>
                </el-link>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="配置管理">
          <div slot="label" @click="handlerAddPackageCategory">
            <el-button class="button-new-tag" size="small" @click="handlerAddPackageCategory">+ {{ $t("添加类目") }}</el-button>
          </div>
          <el-empty :description='$t("还没有商品")'></el-empty>
        </el-tab-pane>
      </el-tabs>

      <!-- 第一个弹框-添加套餐商品 -->
      <dic class="dialogCenter">

        <el-dialog
          :title="$t(packageGoodsDialogTitle)"
          :visible.sync="dialogVisible1"
          width="30%"
          :before-close="handlePackageGoodsClose"
          :close-on-click-modal="false"
        >
          <!-- 表单内容 -->
          <div>

            <!-- 商品信息 表单内容 -->
            <el-form
              size="small"
              v-show="packageGoodsRadioGroup==1"
              :model="packageGoodsForm"
              :rules="packageGoodsRules"
              ref="packageGoodsForm"
              label-width="120px"
              class="demo-ruleForm"
            >
              <el-form-item :label="$t('商品分类')" prop="categoryl3">
                <el-cascader v-model="packageGoodsForm.categoryl3" class="filter-item" clearable :options="categoryList" expand-trigger="hover" @change="handleCategoryChange" :placeholder="$t('Category_Level_3')" :show-all-levels="false"></el-cascader>
              </el-form-item>

              <el-form-item :label="$t('商品名称')" prop="goodsId">
                <el-select
                  :disabled="!packageGoodsForm.categoryl3"
                  v-model="packageGoodsForm.goodsId"
                  class="filter-item"
                  clearable
                  :placeholder="$t('请选择商品名称')"
                  @change="packageGoodsChangeSelect"
                >
                  <el-option
                    v-for="item in goodsList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item :label="$t('商品数量')" prop="quantity">
                {{packageGoodsForm.quantity}}
                <!--                <el-input-number v-model="packageGoodsForm.quantity"  :min="1" :label="$t('请输入数量')"></el-input-number>-->
              </el-form-item>


              <el-form-item label="是否默认">
                <el-switch v-model="packageGoodsForm.isDefault"></el-switch>
              </el-form-item>
            </el-form>


            <p align="center">
              <el-button
                icon="el-icon-success"
                type="primary"
                @click="submitAddPackageGoods"
              >{{ $t("确定") }}</el-button
              >
            </p>
          </div>
        </el-dialog>

        <!-- 第二个弹框-添加套餐商品 -->
        <el-dialog
          :title="packageCategoryForm.id==undefined?'新建类目':'修改类目'"
          :visible.sync="dialogVisibleForPackageCategory"
          width="40%">
          <el-form :model="packageCategoryForm" :rules="packageCategoryFormRules" ref="packageCategoryFormRules" label-width="100px">
            <el-form-item label="类目名称" prop="categoryName">
              <el-input v-model="packageCategoryForm.categoryName"></el-input>
            </el-form-item>
            <!--            <el-form-item label="数量" prop="quantity">
                          <el-input-number v-model="packageCategoryForm.quantity" :min="1" label="数量"></el-input-number>
                          <el-tooltip class="item" effect="dark" content="数量控制该类目下可选择的商品数量" placement="top-start">
                            <i class="el-icon-info">说明</i>
                          </el-tooltip>
                        </el-form-item>-->
            <el-form-item>
              <el-button type="primary" @click="submitPackageCategoryForm('packageCategoryFormRules')">确定</el-button>
              <!--              <el-button  @click="resetPackageCategoryForm('packageCategoryFormRules')">重置</el-button>-->
            </el-form-item>
          </el-form>
        </el-dialog>

      </dic>

    </el-card>

    <div class="op-container">
      <el-button icon="el-icon-error" plain1 @click="handleCancel">{{
        $t("Cancel")
      }}</el-button>
      <el-button
        icon="el-icon-s-promotion"
        plain1
        type="primary"
        @click="submitUpdatePackage"
        >{{ $t("更新套餐") }}</el-button
      >
    </div>
  </div>
</template>

<script>
import {
  detailGoods,
  editGoods,
  listCatAndBrand,
  goodsAddSpec,
  goodsUpdateSpec,
  goodsDeleteSpec,
  goodsAddSpecMer,
  goodsUpdateSpecMer,
  goodsDeleteSpecMer,
  goodsSpecMerList,
  goodsAccessoryMerList,
  goodsAddAccessory,
  goodsUpdateAccessory,
  goodsDeleteAccessory,
  goodsAddProp,
  goodsUpdateProp,
  goodsDeleteProp,
} from "@/api/goods";
import { listCountryRegion, listSubRegion } from "@/api/region";
import { createStorage, uploadPath } from "@/api/storage";
import Editor from "@tinymce/tinymce-vue";
import { MessageBox, Tree } from "element-ui";
import { getToken } from "@/utils/auth";
import { allForPerm } from "@/api/shop";
import { allMerchandise } from "@/api/merchandise";
import { findByRegionId } from "@/api/tax";
import store from "@/store";

//配方
import {
  listFormula,
  addGoodsFormulaCorrelation,
  listGoodsFormulaSpecifications,
  getGoodsFormulaCorrelationDetails,
} from "@/api/formula";
//配方类型
import { listType } from "@/api/formulaType";

import { listFormulaSpecificationsDataProportioning } from "@/api/formulaSpecificationsDataProportioning";
import {
  addFormulaSpecifications,
  updateFormulaSpecifications,
  deleteFormulaSpecifications,
} from "@/api/formulaSpecifications";

//客户定制
import {
  listReplaceableMaterial,
  isCustomization,
  updateIsCustomization,
  addReplaceableMaterial,
  updateReplaceableMaterial,
  deleteReplaceableMaterial,
} from "@/api/replaceableMaterial";
//套餐类目
import {updatePackage,detailPackage,addPackageGoods,listPackageGoods,deletePackageGoods,
  addPackageCategory,listPackageCategory,deletePackageCategory,goodsListPackageCategory
} from "@/api/package"
import {listGoods , listShopGoodsAll,listFilterGoodsByCategoryl3} from '@/api/goods'



export default {
  name: "GoodsDetail",
  components: { Editor },
  data() {
    const validateDouble = (rule, value, callback) => {
      if (!value || !/^[0-9,.]*$/.test(value)) {
        callback(new Error("必须为数字"));
      } else {
        callback();
      }
    };

    const validateRegion = (rule, value, callback) => {
      // 如果是店铺登录则退出不校验
      if (this.shop) {
        callback();
        return;
      }

      if (this.regions.length == 0) {
        callback(new Error("请选择完整的区域信息"));
      }

      let selectedCityIds = [];
      for (let i = 0; i < this.regions.length; i++) {
        let region = this.regions[i];
        let cityId = region.cityId;
        if (!cityId) {
          callback(new Error("请选择完整的区域信息"));
          return;
        } else {
          for (let j = 0; j < selectedCityIds; j++) {
            if (cityId == selectedCityIds[j]) {
              callback(new Error("请勿选择重复的区域信息"));
              return;
            }
          }
          selectedCityIds.push(cityId);
        }
      }

      callback();
    };

    const validatePropertyFormValues = (rule, value, callback) => {
      if (!this.propertyForm.values || this.propertyForm.values.length === 0) {
        callback(new Error("属性不能为空"));
      }

      for (var i = 0; i < this.propertyForm.values.length; i++) {
        if (!this.propertyForm.values[i]) {
          callback(new Error("属性不能为空"));
        }
      }

      callback();
    };
    const weeksTimeMap={
      1: this.$t('星期一'),
      2: this.$t('星期二'),
      3: this.$t('星期三'),
      4: this.$t('星期四'),
      5: this.$t('星期五'),
      6: this.$t('星期六'),
      7: this.$t('星期日')
    }
    return {
      //套餐营业时间
      weeksTimeMap,
      weeksTime:[],
      selectedDate: new Date(),
      showDatepicker: false,
      special:[],

      gallery: [],
      //商品集合 查询条件
      listQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        goodsSn: undefined,
        type: 0,
        name: undefined,
        categoryl3:'',
        sort: 'add_time',
        order: 'desc'
      },
      //商品集合
      goodsList: [],
      // 过滤后的商品集合
      filterGoodsList: [],
      //规格的表单
      packageGoodsForm: {
        packageCategoryId: undefined,
        categoryl3:undefined,
        packageId: undefined,
        goodsId: undefined,
        //picUrl:'',
        quantity: 1,
        //amount:0.00,
        //amountFluctuateValue:1,
        unit:'',
        isDefault:false,
        //规格信息
        //specifications:[],
      },
      //添加 、编辑套餐弹出框标题
      packageGoodsDialogTitle:'添加套餐商品',
      //规格信息 单选值
      selectedSpecification:'',
      //套餐类目id
      packageCategoryId:undefined,
      //套餐商品加载
      listPackageGoodsLoading: false,
      //套餐商品集合
      packageGoodsList:[],
      //添加套餐商品 表单规则
      packageGoodsRules:{
        categoryl3:[{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        goodsId:[{ required: true, message: '请选择商品', trigger: 'blur' }],
        quantity:[{ required: true, message: '商品数量不能为空', trigger: 'blur' }],
        //amount:[{ required: true, message: '商品金额不能为空', trigger: 'blur' }],

      },
      //套餐列表
      packageForm: {
        lumierePackage:{
          id: undefined,
          categoryId: undefined,
          packageNumber: undefined,
          packageName: undefined,
          subhead: undefined,
          amount:0.00,
          packageIntroduction: undefined,
          packageImg: undefined,
          disseminateGallery: undefined,
          packageDetailsIntroduce: undefined,
          operationExplain: undefined,
          weeksTime:[],
        },
        categoryIds:[],
        regionVos:[],
      },
      //消耗系数
      consumeSystemOptions:[
        {
          value: 0.1,
          label: 0.1,
        },
        {
          value: 0.2,
          label: 0.2,
        },
        {
          value: 0.3,
          label: 0.3,
        },
        {
          value: 0.4,
          label: 0.4,
        },
        {
          value: 0.5,
          label: 0.5,
        },
        {
          value: 0.6,
          label: 0.6,
        },
        {
          value: 0.7,
          label: 0.7,
        },
        {
          value: 0.8,
          label: 0.8,
        },
        {
          value: 0.9,
          label: 0.9,
        },
        {
          value: 1.0,
          label: 1.0,
        },
      ],
      //可替换原料唯一
      materialName: undefined,
      //显示商品规格or配方规格
      showGoodsFormulaTable: true,

      //是否定制
      // isCustomization: undefined,
      //客户定制加载
      customizationFormulaSpecificationsMaterialLoading: false,
      //客户定制集合
      customizationFormulaSpecificationsMaterialList: [],
      //切换
      activeName: "first",
      //可替换原料表单
      replaceableMaterialForm: {
        //定制配方
        lumiereCustomizationFormula: {
          goodsId: undefined,
          specificationsId: undefined,
          materialId: undefined,
        },
        //可替换原料
        lumiereReplaceableMaterial: {
          materialName: undefined,
          materialImg: undefined,
          surcharge: undefined,
          specificationsDose: undefined,
          quantity: undefined,
          chargingCondition: undefined,
          chargingConditionNumber: undefined,
          quantityRestrict: undefined,
          unit: undefined,
          consumeSystem: undefined,
          chargingMode: undefined,
        },
      },
      //规格的表单
      formulaSpecificationsForm: {
        id: undefined,
        formulaId: undefined,
        specificationsName: undefined,
        specificationsValue: undefined,
        specificationsImg: undefined,
        specificationsPrice: undefined,
        isDefault: undefined,
        formulaMaterialIds: undefined,
      },
      //弹框显示
      //添加配方规格
      dialogVisible1: false,
      //添加套餐商品 表单切换
      packageGoodsRadioGroup:1,
      //添加套餐商品 商品信息 套餐商品金额选项框
      packageGoodsAmountOptions:[
        {amountFluctuate:'增加',amountFluctuateValue:1}, {amountFluctuate:'减少',amountFluctuateValue:0}
      ],
      //添加套餐商品 商品信息 规格信息单选框
      packageGoodsSpecificationRadio:undefined,
      //编辑配方规格
      dialogVisible2: false,
      //编辑配方规格原料数据配比
      dialogVisible3: false,
      //可替换原料弹框
      dialogVisible4: false,
      //编辑可替换原料弹框
      dialogVisible5: false,
      //是否默认
      isCustomizationChecked: undefined,
      //单独的配方
      formulaForm: {},
      //配方类型列表
      formulaTypeList: [],
      //商品配方规格列表
      goodsFormulaSpecificationsList: [],
      //商品配方规格刷新
      goodsFormulaSpecificationsLoading: false,
      //配方页面刷新
      formulaListLoading: false,
      //配方页面集合
      formulaList: [],
      //配方规格数据配比集合
      formulaSpecificationsDataProportioningList: [],
      //配方规格数据配比刷新
      formulaSpecificationsDataProportioningLoading: false,
      //需要挑战传入的商品配方详情
      formulaDetails: {},

      // 当前店铺
      shop: store.state.user.shop,
      shopRegions: store.state.user.shopRegions,
      shops: [],
      uploadPath,
      vipPriceForm: {},
      stepPriceForms: [{}],
      moneyOfPriceForms: [{}],
      newKeywordVisible: false,
      newKeyword: "",
      keywords: [],
      galleryFileList: [],
      hideUpload: false,

      categoryList: [],
      regionList: [],
      brandList: [],
      categoryIds: [],
      goods: { priceType: "1", gallery: [] },
      regions: [],
      specVisiable: false,
      formulaVisiable: false,
      formulaSpecificationsDataProportioningVisiable: false,
      specForm: { specification: "", value: "", picUrl: "", sort: 0 },
      specEditVisiable: false,
      specEditForm: {
        id: undefined,
        goodsId: undefined,
        specification: undefined,
        value: undefined,
        price: undefined,
        picUrl: undefined,
        sort: undefined,
      },
      specRules: {
        specification: [{ required: true,message: this.$t("请输入规格名"), trigger: "blur" }],
        value: [{ required: true,message: this.$t("请输入规格值"), trigger: "blur" }],
        price: [{ required: true,message: this.$t("请输入价格"), trigger: "blur" }],
        picUrl: [{ required: true,message: this.$t("请输入规格图片"), trigger: "blur" }],
        sort: [{ required: true,message: this.$t("请输入序号"), trigger: "blur" }],
      },
      specMerVisiable: false,
      specMerList: [],
      specMerForm: {
        id: undefined,
        goodsId: undefined,
        goodsSpecificationId: undefined,
        merchandiseId: undefined,
        merchandiseSn: undefined,
        merchandiseName: undefined,
        standard: undefined,
        model: undefined,
        basicUnit: undefined,
        number: undefined,
        consumeRatio: undefined,
      },
      specMerRules: {
        merchandiseId: [{ required: true,message: this.$t("请选择原料"), trigger: "blur" }],
        number: [{ required: true,message: this.$t("请输入数量"), trigger: "blur" }],
        model: [{ required: true,message: this.$t("请输入规格"), trigger: "blur" }],
        consumeRatio: [{ required: true,message: this.$t("请输入消耗系数"), trigger: "blur" }],
      },
      specifications: [
        { specification: "规格", price: 0.0, value: "标准", picUrl: "" },
      ],
      productVisiable: false,
      productForm: {
        id: 0,
        specifications: [],
        price: 0.0,
        number: 0,
        url: "",
        tax: 0.0,
      },
      products: [
        { id: 0, specifications: ["标准"], price: 0.0, number: 0, url: "" },
      ],
      attributeVisiable: false,
      attributeForm: { attribute: "", value: "" },
      attributes: [],
      rules: {
        goodsSn: [
          {
            required: true,
            message: this.$t("Merchandise_ID_must_not_be_empty"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("Merchandise_name_must_not_be_empty"),
            trigger: "blur",
          },
        ],
        regionId: [{ trigger: "change", validator: validateRegion }],
      },
      productRules: {
        number: [
          {
            required: true,
            message: this.$t("Stock_amount_cannot_be_empty"),
            trigger: "blur",
          },
          {
            type: "number",
            message: this.$t("Stock_amount_must_be_a_number"),
            trigger: "blur",
          },
        ],
        sellPrice: [
          {
            required: true,
            message: this.$t("Sale_price_cannot_be_empty"),
            trigger: "change",
          },
          { validator: validateDouble, trigger: "change" },
        ],
        costPrice: [
          {
            required: true,
            message: this.$t("Buy-in_cost_cannot_be_empty"),
            trigger: "change",
          },
          { validator: validateDouble, trigger: "change" },
        ],
        /*          tax: [{ required: true, message: '税率不能为空', trigger: 'change' },
                    { validator: validateDouble, trigger: 'change' }],*/
      },
      editorInit: {
        language: "zh_CN",
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure(this.$t("Upload_failed_please_reupload"));
            });
        },
      },
      taxes: [
        {
          value: 0,
          type: 1,
          enable: false,
        },
        {
          value: 0,
          type: 2,
          enable: false,
        },
        {
          value: 0,
          type: 3,
          enable: false,
        },
      ],
      taxTypeData: [
        {
          value: "GST",
          label: "GST",
        },
        {
          value: "PST",
          label: "PST",
        },
      ],
      costTypeData: [
        {
          value: 0,
          label: this.$t("按次计费"),
        },
        {
          value: 1,
          label: this.$t("按份计费"),
        },
      ],
      // 店铺税类型
      shopTaxTypes: [],
      accessoryVisiable: false,
      accessoryForm: {},
      accessories: [],
      accessoryRules: {
        groupName: [
          {
            required: true,
            message: this.$t("辅料名不能为空"),
            trigger: "blur",
          },
        ],
        merchandiseId: [
          {
            required: true,
            message: this.$t("原料不能为空"),
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: this.$t("辅料价格不能为空"),
            trigger: "blur",
          },
        ],
        number: [
          {
            required: true,
            message: this.$t("辅料数量不能为空"),
            trigger: "blur",
          },
        ],
        costType: [
          {
            required: true,
            message: this.$t("计费类型不能为空"),
            trigger: "blur",
          },
        ],
        consumeRatio: [
          {
            required: true,
            message: this.$t("消耗系数不能为空"),
            trigger: "blur",
          },
        ],
        fewContent: [
          { required: true, message: this.$t("少量不能为空"), trigger: "blur" },
        ],
        muchContent: [
          { required: true, message: this.$t("多加不能为空"), trigger: "blur" },
        ],
        accessoryGroupName: [
          {
            required: true,
            message: this.$t("选项可填[咖啡因｜糖浆｜牛奶｜或其它]"),
            trigger: "blur",
          },
        ],
      },
      merchandise: [],
      propertyVisiable: false,
      propertyForm: {},
      properties: [],
      propertyRules: {
        name: [
          {
            required: true,
            message: this.$t("属性名不能为空"),
            trigger: "blur",
          },
        ],
        sort: [{ required: true }],
        values: [{ validator: validatePropertyFormValues, trigger: "blur" }],
      },
      /**
       * 添加套餐类目
       */
      //弹窗开关
      dialogVisibleForPackageCategory:false,
      //表单值
      packageCategoryForm:{
        categoryName:'',
        quantity:1,
        packageId:undefined,
        id:undefined,
      },
      //表单规则
      packageCategoryFormRules:{
        categoryName: [
          {
            required: true,
            message: this.$t("套餐类目不能为空"),
            trigger: "blur",
          },
        ],
      },
      //套餐类目集合
      packageCategoryList:[],
    };
  },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
  },
  async created() {
    await this.init();
    this.LoadGoodsFormulaSpecificationsInit();
    this.getGoodsFormulaDetails();
    this.whetherCustomization();
    //this.getPackageGoodsList();
    this.getGoodsList();
    this.handlerListPackageCategory(this.$route.query.id);
  },
  methods: {
    //套餐营业时间
    handleShow(){
      if(this.packageForm.lumierePackage.weeksTime==null||this.packageForm.lumierePackage.weeksTime==undefined||this.packageForm.lumierePackage.weeksTime.length==0){
        for (let i = 0; i < 7; i++) {this.weeksTime.push(['23:59:59', '23:59:59']);}
        this.packageForm.lumierePackage.weeksTime=this.weeksTime
      }else {
        this.weeksTime=this.packageForm.lumierePackage.weeksTime
      }
      this.special=this.packageForm.lumierePackage.special
    },
    showDatePicker() {
      this.showDatepicker = !this.showDatepicker;
    },
    //选择了某一天
    handleChangePicker(date){
      const newDate = { specialDate: date, specialTime: ['23:59:59','23:59:59'] };
      const hasDuplicate = this.special.some(item => item.specialDate === newDate.specialDate);
      if (!hasDuplicate) {
        this.special.push(newDate);
        this.special.sort((a, b) => {
          const dateA = new Date(a.specialDate);
          const dateB = new Date(b.specialDate);
          return dateA - dateB;
        });
      } else {
        // 如果存在相同的 specialDate 值，进行相应的处理
        this.$notify({
          title: '警告',
          message: '已存在相同的日期，无法添加重复项',
          type: 'warning'
        });
      }
    },
    handleSpecialTimeDeleted(index){
      this.special.splice(index, 1);
    },

    test(val) {
      console.log(val);
      if (val.length == 3) {
        this.goods.categoryId = val[2];
      }
    },
    init() {
      if (this.$route.query.id == null) {
        return;
      }

      listCatAndBrand().then((response) => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      });

      allForPerm().then((response) => {
        this.shops = response.data.data.list;
      });

      const packageId = this.$route.query.id;
      detailPackage({ id: packageId }).then((response) => {
        this.packageForm = response.data.data;
        if(this.packageForm.lumierePackage.packageImg == undefined){
          this.packageForm.lumierePackage.packageImg = '';
        }

        this.regions = this.packageForm.regionVos;

        console.log(this.packageForm.lumierePackage.disseminateGallery)

        if(this.packageForm.lumierePackage.disseminateGallery != undefined && this.packageForm.lumierePackage.disseminateGallery != ''){
          this.galleryFileList = [];
          const galleryArray = this.packageForm.lumierePackage.disseminateGallery.split(','); // 使用逗号作为分隔符
          for (var i = 0; i < galleryArray.length; i++) {
            this.galleryFileList.push({
              url: galleryArray[i],
            });
          }
        }


        // 初始化区域列表
        this.initRegionList();

        if (keywords !== null) {
          this.keywords = keywords.split(",");
        }
      });



      // //debugger

      // 初始化店铺税务类型
      if (this.shopRegions && this.shopRegions.length == 3) {
        let countryId = this.shopRegions[0].id;
        let provinceId = this.shopRegions[1].id;
        let cityId = this.shopRegions[2].id;
        return findByRegionId(countryId, provinceId, cityId).then(
          (response) => {
            this.shopTaxTypes = response.data.data.list;
          }
        );
      }
    },
    initRegionList() {
      this.regions.forEach((e) => {
        // //debugger
        let region = {
          countrys: [],
          provinces: [],
          citys: [],
          taxTypes: [],
        };
        // 构建国家级别
        listCountryRegion().then((response) => {
          region.countrys = response.data.data.list;
        });

        // 构建省
        let query = {
          id: e.countryId,
          type: 2,
        };
        listSubRegion(query).then((response) => {
          region.provinces = response.data.data.list;
        });

        // 构建城市
        query.id = e.provinceId;
        listSubRegion(query).then((response) => {
          region.citys = response.data.data.list;
        });

        // 加载区域水
        // let cityId = e.cityId
        findByRegionId(e.countryId, e.provinceId, e.cityId).then((response) => {
          region.taxTypes = response.data.data.list;
        });

        this.regionList.push(region);
      });
    },
    addRegion() {
      if(this.regionList.length==0){
        let region = {
          countrys: [],
          provinces: [],
          citys: [],
          taxTypes: []
        }

        listCountryRegion().then(response=>{
          region.countrys = response.data.data.list
        })

        this.regionList.push(region)

        let regionData = {
          countryId: undefined,
          provinceId: undefined,
          cityId: undefined,
          taxTypes: []
        }

        this.regions.push(regionData)
      }

      //复制上一份的数据
      else{
        if(this.regions[0].countryId==undefined){
          this.$notify({
            title: "提示",
            message: "请完善第一条数据",
            type: "warning",
          });
          return;
        }
        this.regionList.push(Object.assign({}, this.regionList[this.regionList.length-1]))
        this.regions.push(Object.assign({}, this.regions[this.regions.length-1]))
      }

    },
    deleteRegion(index) {
      this.regionList.splice(index, 1);
      this.regions.splice(index, 1);
    },
    changeCountry(index, value) {
      this.regionList[index].provinces = [];
      this.regionList[index].citys = [];
      this.regionList[index].taxTypes = [];
      this.regions[index].provinceId = undefined;
      this.regions[index].cityId = undefined;

      let query = {
        id: value,
        type: 2,
      };
      listSubRegion(query).then((response) => {
        this.regionList[index].provinces = response.data.data.list;
      });
    },
    changeProvince(index, value) {
      this.regionList[index].citys = [];
      this.regionList[index].taxTypes = [];
      this.regions[index].cityId = undefined;

      let query = {
        id: value,
        type: 2,
      };
      listSubRegion(query).then((response) => {
        this.regionList[index].citys = response.data.data.list;
      });
    },
    changeCity(index, region, value) {
      let countryId = region.countryId;
      let provinceId = region.provinceId;
      let cityId = region.cityId;
      findByRegionId(countryId, provinceId, cityId).then((response) => {
        this.regionList[index].taxTypes = response.data.data.list;
      });
    },
    handleCategoryChange(value) {
      this.listQuery.categoryl3 = (value && value.length > 0) ? value[value.length - 1] : '';
      this.packageGoodsForm.goodsId = undefined;
      this.getGoodsList(this.listQuery.categoryl3);
      // this.goods.categoryId = value[value.length - 1]
    },
    handleCancel: function () {
      if (this.shop) {
        this.$router.push({ path: "/goods/shop_list" });
      } else {
        this.$router.push({ path: "/goods/package" });
      }
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1);
      this.goods.keywords = this.keywords.toString();
    },
    showInput() {
      this.newKeywordVisible = true;
      this.$nextTick((_) => {
        this.$refs.newKeywordInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword;
      if (newKeyword) {
        this.keywords.push(newKeyword);
        this.goods.keywords = this.keywords.toString();
      }
      this.newKeywordVisible = false;
      this.newKeyword = "";
    },
    uploadPicUrl: function (response) {
      //debugger
      this.packageForm.lumierePackage.packageImg = response.data.url;
    },
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: this.$t("File_upload_exceeded_maximum_value!_Max._5_photos"),
      });
    },
    handleGalleryUrl(response, file, fileList) {
      this.galleryFileList.push({url:response.data.url})
      this.hideUpload = fileList.length >= 5;

    },
    specChanged: function (label) {
      if (label === false) {
        this.specifications = [
          { specification: "规格", value: "标准", picUrl: "" },
        ];
        this.products = [
          { id: 0, specifications: ["标准"], price: 0.0, number: 0, url: "" },
        ];
      } else {
        this.specifications = [];
        this.products = [];
      }
    },
    uploadSpecPicUrl: function (response) {
      this.specForm.picUrl = response.data.url;
    },
    uploadSpecEditPicUrl: function (response) {
      this.specEditForm.picUrl = response.data.url;
    },
    handleSpecificationShow() {
      this.specForm = { specification: "", value: "", picUrl: "" };
      this.specVisiable = true;
    },
    //选择配方页面打开
    handleFormulaShow() {
      this.getFormulaList();
      this.formulaVisiable = true;
    },
    //配方规格详情页面打开
    handleFormulaSpecificationsDataProportioningShow(row) {
      this.getFormulaSpecificationsDataProportioning(row.id);
      this.formulaSpecificationsDataProportioningVisiable = true;
    },
    handleSpecificationAdd() {
      this.$refs["specForm"].validate((valid) => {
        if (valid) {
          const sepcData = {
            goodsId: this.goods.id,
            specification: this.specForm.specification,
            value: this.specForm.value,
            price: this.specForm.price,
            picUrl: this.specForm.picUrl,
            sort: this.specForm.sort,
          };

          goodsAddSpec(sepcData)
            .then((response) => {
              const responseData = response.data.data;

              this.$notify.success({
                title: this.$t("Success!"),
                message: "添加成功",
              });

              responseData.merchandises = [];
              this.specifications.push(responseData);

              // 重新排序
              this.specifications.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.specVisiable = false;
              this.showGoodsFormulaTable = true;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecificationEdit(row) {
      this.specEditForm = {
        id: row.id,
        goodsId: row.goodsId,
        specification: row.specification,
        value: row.value,
        price: row.price,
        picUrl: row.picUrl,
        sort: row.sort,
      };

      this.specEditVisiable = true;
    },
    handleSpecificationEditSubmit() {
      this.$refs["specEditForm"].validate((valid) => {
        if (valid) {
          goodsUpdateSpec(this.specEditForm)
            .then((response) => {
              const responseData = response.data.data;
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 更新本地数据
              this.specifications.forEach((e) => {
                if (e.id == this.specEditForm.id) {
                  e.specification = responseData.specification;
                  e.value = responseData.value;
                  e.price = responseData.price;
                  e.picUrl = responseData.picUrl;
                  e.sort = responseData.sort;
                  e.updateTime = responseData.updateTime;
                }
              });

              // 重新排序
              this.specifications.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.specEditVisiable = false;
              this.specEditForm = {};
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecificationDelete(row) {
      const specId = row.id;
      goodsDeleteSpec(specId)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "删除成功",
          });

          const index = this.specifications.indexOf(row);
          this.specifications.splice(index, 1);
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    loadGoodsSpecMerList(specId, merchandiseId) {
      goodsSpecMerList(specId, merchandiseId)
        .then((response) => {
          this.specMerList = response.data.data;
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    handleAddSpecMer(row) {
      this.specMerForm = {};

      const specId = row.id;
      this.specMerForm.goodsId = row.goodsId;
      this.specMerForm.goodsSpecificationId = specId;
      this.specMerForm.consumeRatio = 1;

      this.loadGoodsSpecMerList(specId, "");
      this.specMerVisiable = true;
    },
    handleEditSpecMer(row) {
      this.specMerForm = JSON.parse(JSON.stringify(row)); // 拷贝对象，防止同步修改
      this.loadGoodsSpecMerList(row.goodsSpecificationId, row.merchandiseId);
      this.specMerVisiable = true;
    },
    handleAddSpecMerSubmit() {
      this.$refs["specMerForm"].validate((valid) => {
        if (valid) {
          goodsAddSpecMer(this.specMerForm)
            .then((response) => {
              const responseData = response.data.data;
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 添加本地数据
              this.specifications.forEach((e) => {
                if (e.id == this.specMerForm.goodsSpecificationId) {
                  if (!e.merchandises) {
                    e.merchandises = [];
                  }
                  e.merchandises.push(responseData);
                }
              });

              this.specMerVisiable = false;
              this.specMerForm = {};
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleEditSpecMerSubmit() {
      this.$refs["specMerForm"].validate((valid) => {
        if (valid) {
          goodsUpdateSpecMer(this.specMerForm)
            .then((response) => {
              const responseData = response.data.data;
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 添加本地数据
              this.specifications.forEach((e) => {
                if (e.id == this.specMerForm.goodsSpecificationId) {
                  e.merchandises.forEach((mer) => {
                    if (mer.id == responseData.id) {
                      mer.merchandiseId = responseData.merchandiseId;
                      mer.merchandiseName = responseData.merchandiseName;
                      mer.merchandiseSn = responseData.merchandiseSn;
                      mer.standard = responseData.standard;
                      mer.model = responseData.model;
                      mer.basicUnit = responseData.basicUnit;
                      mer.consumeRatio = responseData.consumeRatio;
                      mer.number = responseData.number;
                    }
                  });
                }
              });

              this.specMerVisiable = false;
              this.specMerForm = {};
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecMerSubmit() {
      const id = this.specMerForm.id;
      if (id) {
        this.handleEditSpecMerSubmit();
      } else {
        this.handleAddSpecMerSubmit();
      }
    },
    handleDeleteSpecMer(row) {
      const id = row.id;
      goodsDeleteSpecMer(id)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "操作成功",
          });

          // 删除本地数据
          this.specifications.forEach((e) => {
            const index = e.merchandises.indexOf(row);
            if (index >= 0) {
              e.merchandises.splice(index, 1);
            }
          });
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    changeSpecMerFormMerchandise(value) {
      this.specMerList.forEach((e) => {
        if (e.id === value) {
          this.specMerForm.unit = e.unit;
          this.specMerForm.merchandiseSn = e.merchandiseSn;
          this.specMerForm.merchandiseName = e.name;
          this.specMerForm.standard = e.standard;
          this.specMerForm.model = e.model;
          this.specMerForm.basicUnit = e.basicUnit;
        }
      });
    },
    specToProduct() {
      if (this.specifications.length === 0) {
        return;
      }
      // 根据specifications创建临时规格列表
      var specValues = [];
      var spec = this.specifications[0].specification;
      var values = [];
      values.push(0);

      for (var i = 1; i < this.specifications.length; i++) {
        const aspec = this.specifications[i].specification;

        if (aspec === spec) {
          values.push(i);
        } else {
          specValues.push(values);
          spec = aspec;
          values = [];
          values.push(i);
        }
      }
      specValues.push(values);

      // 根据临时规格列表生产货品规格
      // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
      var productsIndex = 0;
      var products = [];
      var combination = [];
      var n = specValues.length;
      for (var s = 0; s < n; s++) {
        combination[s] = 0;
      }
      var index = 0;
      var isContinue = false;
      do {
        var specifications = [];
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]];
          specifications.push(this.specifications[z].value);
        }
        products[productsIndex] = {
          id: productsIndex,
          specifications: specifications,
          price: 0.0,
          number: 0,
          url: "",
        };
        productsIndex++;

        index++;
        combination[n - 1] = index;
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0;
            index = 0;
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1;
            }
          }
        }
        isContinue = false;
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true;
          }
        }
      } while (isContinue);

      this.products = products;
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row);
      this.productVisiable = true;
    },
    uploadProductUrl: function (response) {
      this.productForm.url = response.data.url;
    },
    handleProductEdit() {
      for (var i = 0; i < this.products.length; i++) {
        const v = this.products[i];
        if (v.id === this.productForm.id) {
          this.products.splice(i, 1, this.productForm);
          break;
        }
      }
      this.productVisiable = false;
    },
    handleAttributeShow() {
      this.attributeForm = {};
      this.attributeVisiable = true;
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm);
      this.attributeVisiable = false;
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row);
      this.attributes.splice(index, 1);
    },
    handleStepAdd(row) {
      this.stepPriceForms.push({
        number: undefined,
        price: undefined,
      });
    },
    handleStepDelete(scope) {
      if (this.stepPriceForms.length > 1) {
        this.stepPriceForms.splice(scope.$index, 1);
      } else {
        this.stepPriceForms[0] = {
          number: undefined,
          price: undefined,
        };
      }
    },
    handleMoneyOfAdd(row) {
      this.moneyOfPriceForms.push({
        maxPrice: undefined,
        minusPrice: undefined,
      });
    },
    handleMoneyOfDelete(scope) {
      if (this.moneyOfPriceForms.length > 1) {
        this.moneyOfPriceForms.splice(scope.$index, 1);
      } else {
        this.moneyOfPriceForms[0] = {
          maxPrice: undefined,
          minusPrice: undefined,
        };
      }
    },
    handleRemove: function(file, fileList) {
      // 通过遍历找到要移除的文件对象的索引
      let indexToRemove = -1;
      for (let i = 0; i < this.galleryFileList.length; i++) {
        if (this.galleryFileList[i].url === file.url) {
          indexToRemove = i;
          break;
        }
      }
      if (indexToRemove > -1) {
        // 根据找到的索引移除对应的文件对象
        this.galleryFileList.splice(indexToRemove, 1);
        this.hideUpload = fileList.length >= 5;
      }
      console.log('updatedsds', this.galleryFileList);
      /*for (var i = 0; i < this.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.gallery[i] === url) {
          this.gallery.splice(i, 1)
        }
      }*/
    },
    handleTabSwitch: function (tab) {
      if (tab.name == 1) {
        this.goods.priceType = "1";
        this.moneyOfPriceForms = [{}];
        this.stepPriceForms = [{}];
      } else if (tab.name == 2) {
        this.goods.priceType = "2";
        this.vipPriceForm = {};
        this.moneyOfPriceForms = [{}];
      } else {
        this.goods.priceType = "3";
        this.vipPriceForm = {};
        this.stepPriceForms = [{}];
      }
    },
    handleEdit: function () {
      const finalGoods = {
        goods: this.goods,
        regions: this.regions,
        specifications: this.specifications,
        // products: [this.productForm],
        attributes: this.attributes,
        accessories: this.accessories,
        // goodsTaxes: this.taxes
      };
      this.productForm.taxTypes = [];
      this.taxes.forEach((tax) => {
        if (tax.enable && this.productForm.taxTypes.indexOf(tax) < 0) {
          this.productForm.taxTypes.push(tax.type);
        }
      });
      if (this.goods.priceType == "1") {
        finalGoods.vipPrice = this.vipPriceForm;
      } else if (this.goods.priceType == "2") {
        finalGoods.ladderPrices = this.stepPriceForms;
      } else if (this.goods.priceType == "3") {
        finalGoods.maxMinusPrices = this.moneyOfPriceForms;
      }
      if (this.goods.shopId) {
        this.shops.forEach((shop) => {
          if (this.goods.shopId == shop.id) {
            this.goods.shopName = shop.name;
          }
        });
      }

      let regions = finalGoods.regions;
      for (let regionsKey in regions) {
        if (
          regions[regionsKey].countryId == undefined ||
          regions[regionsKey].provinceId == undefined ||
          regions[regionsKey].cityId == undefined
        ) {
          regions.splice(regionsKey);
        }
      }

      this.$refs["goodsForm"].validate((valid) => {
        if (valid) {
          editGoods(finalGoods)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });
              if (this.shop) {
                this.$router.push({ path: "/goods/shop_list" });
              } else {
                this.$router.push({ path: "/goods/list" });
              }
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecRemove: function () {
      this.specForm.picUrl = undefined;
    },
    handleSpecEditRemove() {
      this.specEditForm.picUrl = undefined;
    },
    handleGoodsPicRemove: function () {
      this.packageForm.lumierePackage.packageImg = undefined;
    },
    filterTaxType(type) {
      if (type == 1) {
        return this.$t("国税");
      } else if (type == 2) {
        return this.$t("省税");
      } else if (type == 3) {
        return this.$t("地方税");
      }
    },
    loadAllMerchandise() {
      allMerchandise({ goodsId: this.$route.query.id }).then((response) => {
        this.merchandise = response.data.data;
      });
    },
    handleAccessoryShow() {
      this.loadAllMerchandise();
      this.accessoryForm = {
        accessoryGroupName: "",
        groupName: "",
        name: "",
        price: 0.0,
        consumeRatio: 1,
      };
      this.accessoryVisiable = true;
    },
    handleAccessoryDelete(row) {
      goodsDeleteAccessory(row.id)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "操作成功",
          });
          const index = this.accessories.indexOf(row);
          this.accessories.splice(index, 1);
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    handleAccessoryEdit(row) {
      this.loadAllMerchandise();
      this.accessoryForm = JSON.parse(JSON.stringify(row)); // 拷贝对象，防止同步修改
      this.accessoryVisiable = true;
    },
    handleAccessoryAdd() {
      const id = this.accessoryForm.id;
      if (id) {
        this.handleAccessoryEditSubmit();
      } else {
        this.handleAccessoryAddSubmit();
      }
    },
    handleAccessoryAddSubmit() {
      this.accessoryForm.goodsId = this.goods.id;
      this.$refs["accessoryForm"].validate((valid) => {
        if (valid) {
          goodsAddAccessory(this.accessoryForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "添加成功",
              });

              const responseData = response.data.data;
              this.accessories.push(responseData);
              this.accessoryVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleAccessoryEditSubmit() {
      this.accessoryForm.goodsId = this.goods.id;
      this.$refs["accessoryForm"].validate((valid) => {
        if (valid) {
          goodsUpdateAccessory(this.accessoryForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 更新本地信息
              const responseData = response.data.data;
              this.accessories.forEach((e) => {
                if (e.id == responseData.id) {
                  e.groupName = responseData.groupName;
                  e.groupNameEn = responseData.groupNameEn;
                  e.price = responseData.price;
                  e.merchandiseId = responseData.merchandiseId;
                  e.name = responseData.name;
                  e.number = responseData.number;
                  e.consumeRatio = responseData.consumeRatio;
                  e.costType = responseData.costType;
                }
              });

              this.accessoryVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }

        const goodsId = this.$route.query.id;
        detailGoods(goodsId).then((response) => {
          this.accessories = response.data.data.accessories || [];
        });
      });
    },
    handleAccessoryMerChange() {
      let m = this.merchandise.find((item) => {
        if (item.id == this.accessoryForm.merchandiseId) {
          return item;
        }
      });
      this.accessoryForm.groupName = m.name;
      this.accessoryForm.name = m.name;
      this.accessoryForm.model = m.model;
      this.accessoryForm.unit = m.unit;
      this.accessoryForm.basicUnit = m.basicUnit;
    },
    //改版
    handleAccessoryMerChangeNew() {
      let m = this.merchandise.find((item) => {
        if (item.name == this.replaceableMaterialForm.lumiereReplaceableMaterial.materialName) {
          return item;
        }
      });
      this.accessoryForm.groupName = m.name;
      this.accessoryForm.name = m.name;
      this.accessoryForm.model = m.model;
      this.accessoryForm.unit = m.unit;
      this.accessoryForm.basicUnit = m.basicUnit;
    },
    getCostType(costType) {
      let label = "";
      this.costTypeData.forEach((e) => {
        if (e.value == costType) {
          label = e.label;
        }
      });

      return label;
    },
    handlePropertyShow() {
      this.propertyForm = { name: "", sort: 0, values: [] };
      this.propertyVisiable = true;
    },
    handlePropertyValueAdd() {
      this.propertyForm.values.push("");
    },
    handlePropertyValueDelete(index) {
      this.propertyForm.values.splice(index, 1);
    },
    handlePropertyDelete(row) {
      goodsDeleteProp(row.id)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "操作成功",
          });
          const index = this.properties.indexOf(row);
          this.properties.splice(index, 1);
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    handlePropertyEdit(row) {
      this.propertyForm = row;
      this.propertyVisiable = true;
    },
    handlePropertyAdd() {
      const id = this.propertyForm.id;
      if (id) {
        this.handlePropertyEditSubmit();
      } else {
        this.handlePropertyAddSubmit();
      }
    },
    handlePropertyAddSubmit() {
      this.propertyForm.goodsId = this.goods.id;
      this.$refs["propertyForm"].validate((valid) => {
        if (valid) {
          goodsAddProp(this.propertyForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "添加成功",
              });

              const responseData = response.data.data;
              this.properties.push(responseData);

              // 重新排序
              this.properties.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.propertyVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handlePropertyEditSubmit() {
      this.propertyForm.goodsId = this.goods.id;
      this.$refs["propertyForm"].validate((valid) => {
        if (valid) {
          goodsUpdateProp(this.propertyForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 更新本地信息
              const responseData = response.data.data;
              this.properties.forEach((e) => {
                if (e.id == responseData.id) {
                  e.name = responseData.name;
                  e.sort = responseData.sort;
                  e.values = responseData.values;
                }
              });

              // 重新排序
              this.properties.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.propertyVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },

    //配方列表查询
    getFormulaList() {
      var listFormulaQuery = {
        page: 1,
        limit: 10,
        classificationName: undefined,
        formulaTypeId: undefined,
      };
      this.formulaListLoading = true;
      listFormula(listFormulaQuery)
        .then((response) => {
          this.formulaList = response.data.data.list;
          this.formulaListLoading = false;
        })
        .catch(() => {
          this.formulaList = [];
          this.formulaListLoading = false;
        });
      //选择配方时获取配方类型
      this.getFormulaTypeList();
    },

    //获取配方类型列表
    getFormulaTypeList() {
      var listFormulaTypeQuery = {
        page: 1,
        limit: 10,
        classificationName: undefined,
        formulaTypeId: undefined,
      };
      listType(listFormulaTypeQuery)
        .then((response) => {
          this.formulaTypeList = response.data.data.list;
        })
        .catch(() => {
          this.formulaTypeList = [];
        });
    },

    //获取配方类型名称
    formateFormulaType(row) {
      for (let lengthKey in this.formulaTypeList) {
        if (this.formulaTypeList[lengthKey].id == row.formulaTypeId) {
          return this.formulaTypeList[lengthKey].formulaTypeName;
        }
      }
    },

    //获取配方类型颜色
    formateFormulaTypeColour(row) {
      for (let lengthKey in this.formulaTypeList) {
        if (this.formulaTypeList[lengthKey].id == row.formulaTypeId) {
          return this.formulaTypeList[lengthKey].typeColour;
        }
      }
    },

    //选择配方列表单选触发
    handleCurrentChange(val) {
      console.log(val);
      this.formulaForm = val;
    },

    //选择配方列表提交
    sumbitGoodsFormula() {
      console.log(this.formulaForm.id);
      console.log(this.goods.id);
      var goodsFormulaCorrelation = {
        goodsId: this.goods.id,
        formulaId: this.formulaForm.id,
      };
      addGoodsFormulaCorrelation(goodsFormulaCorrelation)
        .then((res) => {
          if (res.data.data == 100) {
            this.$notify({
              title: "警告",
              message: "这是一条警告的提示消息",
              type: "warning",
            });
            // this.detailGoods(goodsId).then((response) => {
            //   this.specifications = response.data.data.specifications;
            // });
          } else {
            this.formulaVisiable = false;
            this.$notify({
              title: "成功",
              message: "切换成功",
              type: "success",
            });
          }
          this.LoadGoodsFormulaSpecifications();
          this.init();
          this.whetherCustomization();
          this.showGoodsFormulaTable = false;
        })
        .catch((error) => {
          this.$notify.error({
            title: "错误",
            message: "创建失败",
          });
        });
    },

    //加载商品配方规格数据
    LoadGoodsFormulaSpecifications() {
      this.goodsFormulaSpecificationsLoading = true;
      var listQuery = {
        goodsId: this.$route.query.id,
      };
      listGoodsFormulaSpecifications(listQuery)
        .then((response) => {
          this.goodsFormulaSpecificationsList = response.data.data.list;
          if(this.goodsFormulaSpecificationsList != []){
            this.showGoodsFormulaTable = false;
            this.goodsFormulaSpecificationsLoading = false;
          }
        })
        .catch(() => {
          this.goodsFormulaSpecificationsList = [];
          this.goodsFormulaSpecificationsLoading = false;
        });
    },

    //加载商品配方规格数据
    LoadGoodsFormulaSpecificationsInit() {
      this.goodsFormulaSpecificationsLoading = true;
      var listQuery = {
        goodsId: this.$route.query.id,
      };
      listGoodsFormulaSpecifications(listQuery)
        .then((response) => {
          console.log('12121'+JSON.stringify(response.data.data))
          this.goodsFormulaSpecificationsList = response.data.data.list;
          this.activeName = this.goodsFormulaSpecificationsList[0].id + "";
          if(this.goodsFormulaSpecificationsList != []){
             this.handleClick(
                { name: this.goodsFormulaSpecificationsList[0].id },
                null
              );
            this.showGoodsFormulaTable = false;
            this.goodsFormulaSpecificationsLoading = false;
          }
        })
        .catch(() => {
          this.goodsFormulaSpecificationsList = [];
          this.goodsFormulaSpecificationsLoading = false;
        });
    },

    //通过规格id查询配方规格数据配比
    getFormulaSpecificationsDataProportioning(formulaSpecificationsId) {
      this.formulaSpecificationsDataProportioningLoading = true;
      var formulaSpecificationsDataProportioning = {
        page: 1,
        limit: 10,
        formulaSpecificationsId: parseInt(formulaSpecificationsId, 10),
      };
      listFormulaSpecificationsDataProportioning(
        formulaSpecificationsDataProportioning
      )
        .then((response) => {
          this.formulaSpecificationsDataProportioningList =
            response.data.data.list;
          this.formulaSpecificationsDataProportioningLoading = false;
        })
        .catch(() => {
          this.formulaSpecificationsDataProportioningList = [];
          this.formulaSpecificationsDataProportioningLoading = false;
        });
    },

    //去编辑
    handeleAddSpecifications() {
      console.log(this.formulaDetails);
      this.$router.push({
        path: "/formula/formulaSpecifications",
        // query: { id: row.id, type: 1, showType: row.status == 1 ? 2 : 1 },
        query: {
          formulaMaterialList: this.formulaDetails.children,
          formulaId: this.formulaDetails.id,
          formulaName: this.formulaDetails.formulaName,
        },
      });
    },

    getGoodsFormulaDetails() {
      var listQuery = {
        goodsId: this.$route.query.id,
      };
      getGoodsFormulaCorrelationDetails(listQuery)
        .then((response) => {
          this.formulaDetails = response.data.data;
        })
        .catch(() => {
          this.formulaDetails = [];
        });
    },

    //关闭规格弹窗
    handleCloseFormulaSpecifications(done) {
      this.init();
      done();
    },
    //编辑规格弹窗
    handerEditFormulaSpecifications(row) {
      this.dialogVisible2 = true;
      this.formulaSpecificationsForm.id = row.id;
      this.formulaSpecificationsForm.formulaId = row.formulaId;
      this.formulaSpecificationsForm.specificationsName =
        row.specificationsName;
      this.formulaSpecificationsForm.specificationsValue =
        row.specificationsValue;
      this.formulaSpecificationsForm.specificationsImg = row.specificationsImg;
      this.formulaSpecificationsForm.specificationsPrice =
        row.specificationsPrice;
      this.formulaSpecificationsForm.isDefault = row.isDefault;
      this.formulaSpecificationsForm.formulaMaterialIds = undefined;
    },

    //删除规格
    handerDeleteFormulaSpecifications(row) {
      var formulaSpecificationsForm = {
        id: row.id,
      };
      this.$confirm("确认删除？")
        .then((_) => {
          deleteFormulaSpecifications(formulaSpecificationsForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
              this.LoadGoodsFormulaSpecifications();
            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },

    //切换规格
    handleClick(tab, event) {
      console.log(1231232132123213);
      console.log(tab, event);
      console.log(tab.name);
      //debugger
      this.getCustomizationFormulaSpecificationsMaterial(tab.name);
      this.replaceableMaterialForm.lumiereCustomizationFormula.specificationsId =
        parseInt(tab.name, 10);

      // this.formulaDataProportioningForm.formulaSpecificationsId = parseInt(
      //   tab.name,
      //   10
      // );
    },

    //客户定制查询
    getCustomizationFormulaSpecificationsMaterial(formulaSpecificationsId) {
      this.customizationFormulaSpecificationsMaterialLoading = true;
      var customizationFormulaSpecificationsMaterial = {
        goodsId: this.$route.query.id,
        specificationsId: parseInt(formulaSpecificationsId, 10),
      };
      listReplaceableMaterial(customizationFormulaSpecificationsMaterial)
        .then((response) => {
          this.customizationFormulaSpecificationsMaterialList =
            response.data.data.list;
          this.customizationFormulaSpecificationsMaterialLoading = false;
        })
        .catch(() => {
          this.customizationFormulaSpecificationsMaterialList = [];
          this.customizationFormulaSpecificationsMaterialLoading = false;
        });
    },

    //是否定制
    whetherCustomization() {
      var goodsFormulaCorrelation = {
        goodsId: this.$route.query.id,
      };
      isCustomization(goodsFormulaCorrelation)
        .then((response) => {
          this.isCustomizationChecked = response.data.data.isCustomization;
          this.LoadGoodsFormulaSpecificationsInit();
        })
        .catch(() => {
          this.isCustomizationChecked = undefined;
        });
    },

    //修改是否定制
    updateWhetherCustomization() {
      var goodsFormulaCorrelation = {
        goodsId: this.$route.query.id,
        isCustomization: this.isCustomizationChecked ? true : false,
      };
      updateIsCustomization(goodsFormulaCorrelation)
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
          });
        })
        .catch((res) => {
          this.$notify.error({
            title: "错误",
            message: "操作失败",
          });
        });
    },

    //添加可替换原料弹窗
    handerAddReplaceableMaterial(row) {
      console.log(888888888888888888888888888888);
      console.log(row);
      this.dialogVisible4 = true;
      this.replaceableMaterialForm.lumiereCustomizationFormula.goodsId =
        parseInt(this.$route.query.id, 10);
      this.replaceableMaterialForm.lumiereCustomizationFormula.formulaId =
        row.adminFormulaMaterialReplaceableMaterialDTO.formulaId;
      this.replaceableMaterialForm.lumiereCustomizationFormula.materialId =
        row.adminFormulaMaterialReplaceableMaterialDTO.id;

      const result = this.getNumberAndSymbolFromComparisonString(row.chargingCondition)
      this.replaceableMaterialForm.lumiereReplaceableMaterial = {
        materialName: row.adminFormulaMaterialReplaceableMaterialDTO.materialName,
        materialImg: row.adminFormulaMaterialReplaceableMaterialDTO.materialImg,
        surcharge: row.surcharge,
        specificationsDose: row.specificationsDose,
        quantity: row.quantity,
        chargingCondition: result.symbol,
        chargingConditionNumber: result.number,
        quantityRestrict: row.quantityRestrict,
        chargingMode: row.chargingMode,
        unit: row.unit,
        consumeSystem: row.consumeSystem
      };
      //加载原料
      this.handleAccessoryShow();
      this.accessoryForm.basicUnit = row.unit

      this.materialName = row.adminFormulaMaterialReplaceableMaterialDTO.materialName
    },

    //添加可替换原料
    submitAddReplaceableMaterial(form) {

      if(this.materialName  === form.lumiereReplaceableMaterial.materialName){
        this.$notify.error({
          title: "错误",
          message: "原料已被使用",
        });
        return;
      }

      form.lumiereReplaceableMaterial.chargingCondition = form.lumiereReplaceableMaterial.chargingCondition + form.lumiereReplaceableMaterial.chargingConditionNumber;
      var lumiereReplaceableMaterialVO = JSON.stringify(form);
      console.log(lumiereReplaceableMaterialVO)
      addReplaceableMaterial(form)
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "添加成功",
            type: "success",
          });
          this.dialogVisible4 = false;
          // console.log(form)
          // console.log(88888)
          // console.log(this.customizationFormulaSpecificationsMaterialList)


          form.lumiereReplaceableMaterial.id = res.data.data;
          //添加原料不刷新页面，手动添加
          const materialId = form.lumiereCustomizationFormula.materialId;
          const index = this.customizationFormulaSpecificationsMaterialList.findIndex(item => item.adminFormulaMaterialReplaceableMaterialDTO.id === materialId);

          if (index !== -1) {
            this.customizationFormulaSpecificationsMaterialList[index].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.splice(this.customizationFormulaSpecificationsMaterialList[index].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.length,0,form.lumiereReplaceableMaterial)
            //this.$set(this.customizationFormulaSpecificationsMaterialList[index], 'replaceableMaterialList', this.customizationFormulaSpecificationsMaterialList[index].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.map(re=> Object.assign({},re)));
          }


        })
        .catch((res) => {
          this.$notify.error({
            title: "错误",
            message: "添加失败",
          });
        });
    },

    //编辑可替换原料弹窗
    handerUpdateReplaceableMaterial(row) {
      console.log(99)
      console.log(row);
      this.dialogVisible5 = true;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.id = row.id;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.materialName = row.materialName;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.specificationsDose = row.specificationsDose;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.quantity = row.quantity;
      const result = this.getNumberAndSymbolFromComparisonString(
        row.chargingCondition
      );
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition = result.symbol;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingConditionNumber = result.number;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.surcharge = row.surcharge;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.quantityRestrict = row.quantityRestrict;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.unit = row.unit;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingMode = row.chargingMode;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.consumeSystem = row.consumeSystem;
      //加载原料
      this.handleAccessoryShow();

      this.accessoryForm.basicUnit = row.unit
    },

    //提交编辑可替换原料
    submitUpdateReplaceableMaterial(form) {
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition =
        this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition +
        this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingConditionNumber;
      updateReplaceableMaterial(this.replaceableMaterialForm.lumiereReplaceableMaterial)
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "编辑成功",
            type: "success",
          });
          this.dialogVisible5 = false;

          //debugger
          //父位置
          let parentIndex = -1;
          //子位置
          let childIndex = -1;

          parentIndex = this.customizationFormulaSpecificationsMaterialList.findIndex(item => {
              childIndex = item.adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.findIndex(itemChildren => itemChildren.id === res.data.data);
              return childIndex !== -1; // 如果找到子元素，则返回true，终止遍历
          });

          if (childIndex !== -1) {
            this.customizationFormulaSpecificationsMaterialList[parentIndex].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.splice(childIndex,1,form)
          }

        })
        .catch((res) => {
          this.$notify.error({
            title: "错误",
            message: "编辑失败",
          });
        });
    },

    //删除可替换原料
    handerDeleteReplaceableMaterial(row) {
      var replaceableMaterialForm = {
        id: row.id
      };
      this.$confirm("确认删除？")
        .then((_) => {
          deleteReplaceableMaterial(replaceableMaterialForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });

              //父位置
              let parentIndex = -1;
              //子位置
              let childIndex = -1;

              parentIndex = this.customizationFormulaSpecificationsMaterialList.findIndex(item => {
                  childIndex = item.adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.findIndex(itemChildren => itemChildren.id === replaceableMaterialForm.id);
                  return childIndex !== -1; // 如果找到子元素，则返回true，终止遍历
              });

              if (childIndex !== -1) {
                this.customizationFormulaSpecificationsMaterialList[parentIndex].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.splice(childIndex,1)
              }

            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },

    //分割特殊字符和数字
    getNumberAndSymbolFromComparisonString(str) {
      // 检查输入是否为非空字符串
      if (typeof str !== "string" || str.trim() === "") {
        return { number: null, symbol: null };
      }

      // 使用正则表达式分别提取符号和数字
      const symbolMatch = str.match(/[<>=!]+/); // 匹配符号
      const numberMatch = str.match(/-?\d+(\.\d+)?/); // 匹配整数和浮点数，包括负数

      // 提取符号和数字
      const symbol = symbolMatch ? symbolMatch[0] : null;
      const number = numberMatch ? parseFloat(numberMatch[0]) : null;

      return { number, symbol };
    },

    //修改套餐
    submitUpdatePackage(){
      if(this.packageForm.lumierePackage.weeksTime==undefined||this.packageForm.lumierePackage.weeksTime.filter(item => item !== null).length!=7){
        this.$notify({
          title: '警告',
          message: '请完善周一至周日的服务时间！再继续...',
          type: 'warning'
        });
        return;
      }

      // 在提交前确保数据格式为两位小数
      this.packageForm.lumierePackage.amount = parseFloat(this.packageForm.lumierePackage.amount).toFixed(2);
      this.packageForm.lumierePackage.disseminateGallery = this.galleryFileList
          .map(file => file .url) // 提取每个文件的 URL
          .join(','); // 使用逗号拼接成字符串
      updatePackage(this.packageForm).then(res=>{
        this.$notify.success({
          title: this.$t('Success!'),
          message: '修改成功'
        })
        this.$router.push({ path: '/goods/package'})
      }).catch(response => {
        this.$notify.error({
          title: this.$t('失败'),
          message: this.$t('套餐修改失败')
        })
      })
    },

    //套餐商品列表查询
    /*getPackageGoodsList() {
      const packageId = this.$route.query.id;
      var listPackageGoodsQuery = {
        packageId: packageId,
      };
      this.listPackageGoodsLoading = true;
      listPackageGoods(listPackageGoodsQuery)
        .then((response) => {
          this.packageGoodsList = response.data.data;
          this.listPackageGoodsLoading = false;
        })
        .catch(() => {
          this.packageGoodsList = [];
          this.listPackageGoodsLoading = false;
        });
    },*/

    //添加套餐商品弹窗
    handerPackageGoods() {
      this.dialogVisible1 = true;
      this.packageGoodsDialogTitle = '添加套餐商品';
      this.packageGoodsForm = {
        goodsId: undefined,
        quantity: 1,
        isDefault:false,
        amount:0.00,
        amountFluctuate:'增加',
      };
    },

    //去配方管理
    /*goFormulaList(){
      this.$router.push({ path: '/formula/formulaList' })
    },*/

    //关闭套餐商品弹窗
    handlePackageGoodsClose(done){
      this.init();
      done();
    },

    //查询所有商品
    getGoodsList(categoryl3) {
      listFilterGoodsByCategoryl3({categoryl3:categoryl3}).then(response => {
        this.goodsList = response.data.data
      }).catch(() => {
        this.goodsList = []
      })
    },

    handleAmountChanged(val, newval ){
      this.$forceUpdate()
      console.log('handleAmountChanged',val,newval)
    },

    //添加套餐商品
    submitAddPackageGoods() {
      const packageId = this.$route.query.id;
      this.packageGoodsForm.packageId = packageId;
      this.packageGoodsForm.packageCategoryId = this.packageCategoryId;
      this.packageGoodsForm.categoryId = this.packageGoodsForm.categoryl3[this.packageGoodsForm.categoryl3.length - 1];

      /*if (this.packageGoodsForm.specifications.length > 0) {
        this.packageGoodsForm.specifications.forEach(specification => {
          specification.isDefault = specification.specification === this.selectedSpecification;

          // 根据增加、减少设置值并保留两位小数
          if (specification.selectedAmountFluctuate === 1) {
            specification.amount = Math.abs(specification.amount).toFixed(2);
          } else {
            specification.amount = (-Math.abs(specification.amount)).toFixed(2);
          }
        });
      }*/

      // 根据增加、减少设置值并保留两位小数
      /*if (this.packageGoodsForm.amountFluctuateValue === 1) {
        this.packageGoodsForm.amount = Math.abs(this.packageGoodsForm.amount).toFixed(2);
      } else {
        this.packageGoodsForm.amount = (-Math.abs(this.packageGoodsForm.amount)).toFixed(2);
      }*/

      //return;
      addPackageGoods(this.packageGoodsForm)
        .then((res) => {
          if (res.data.data == 100) {
            this.$notify({
              title: "警告",
              message: "这是一条警告的提示消息",
              type: "warning",
            });
          } else {
            this.dialogVisible1 = false;
            this.$notify({
              title: "成功",
              message: "成功",
              type: "success",
            });
            //存在类目 就获取下列商品 套餐商品列表查询
            goodsListPackageCategory({packageId:packageId,packageCategoryId:this.packageCategoryId}).then((res) => {
              this.packageGoodsList = res.data.data;
              this.listPackageGoodsLoading = false;
            })
            this.$refs["packageGoodsForm"].resetFields();
          }
        })
        .catch((error) => {
          console.error("请求错误：", error);
            if (error.data.errno == 1004) {
              this.$notify.error({
                title: "错误",
                message: error.data.errmsg,
              });
            } else {
              this.$notify.error({
                title: "错误",
                message: "编辑失败",
              });
            }
        });
    },
    handlerDeletePackageGoods(row) {
      this.$confirm("确认删除？")
        .then((_) => {
          deletePackageGoods(row.id)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
              //在列表中去掉当前行
              this.packageGoodsList = this.packageGoodsList.filter(item => item.id !== row.id);
              //this.getPackageGoodsList();
            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },

    //编辑 套餐商品 弹出框
    handlerEditPackageGoods(row){
      this.getGoodsList()
      this.dialogVisible1 = true;
      this.packageGoodsDialogTitle = '编辑套餐商品';
      this.packageGoodsForm = row;
      this.packageGoodsForm.categoryl3 = row.categoryId;
      this.packageGoodsForm.picUrl = row.goods.picUrl;

      this.packageGoodsForm.amountFluctuateValue = row.amount>=0?1:0;
      row.specifications.forEach(specification => {
        if(specification.isDefault){
          this.selectedSpecification = specification.specification;
        }
      });
    },

    //添加套餐类目
    handlerAddPackageCategory(){
      this.packageCategoryForm = {}
      this.dialogVisibleForPackageCategory = true;
      this.packageCategoryForm.packageId  = this.$route.query.id;
      this.packageCategoryForm.quantity  = 1;
    },

    //编辑套餐类目
    handlerUpdatePackageCategory(packageCategory){
      this.packageCategoryForm = packageCategory;
      this.dialogVisibleForPackageCategory = true;
    },


    //切换套餐类目
    handleClickCategoryTabs(tab, event) {
      if(!tab.name)return;
      this.listPackageGoodsLoading = true;
      this.packageCategoryId = tab.name
      //存在类目 就获取下列商品 套餐商品列表查询
      goodsListPackageCategory({packageId:this.$route.query.id,packageCategoryId:this.packageCategoryId}).then((res) => {
        this.packageGoodsList = res.data.data;
        this.listPackageGoodsLoading = false;
      })
    },
    //切换套餐类目
    /*handlePackageCategoryTabClick(item, event) {
      this.listPackageGoodsLoading = true;
      this.packageCategoryId = item.id
      //存在类目 就获取下列商品 套餐商品列表查询
      goodsListPackageCategory({packageId:this.$route.query.id,packageCategoryId:this.packageCategoryId}).then((res) => {
        this.packageGoodsList = res.data.data;
        this.listPackageGoodsLoading = false;
      })
    },*/

    //添加套餐类目 商品信息 选择商品改变
    packageGoodsChangeSelect(packageGoods){
      //this.packageGoodsForm.specifications = [];

      const selectedGoods = this.goodsList.find(goods => goods.id === packageGoods);
      //this.packageGoodsForm.picUrl = selectedGoods.picUrl;
      //this.packageGoodsForm.unit = selectedGoods.unit;
      this.packageGoodsForm.goodsId = selectedGoods.id;


      //改变规格信息表 的规格选项
      /*listGoodsFormulaSpecifications({goodsId: this.packageGoodsForm.goodsId})
          .then((response) => {
            //先查找商品是否有配方 获得配方的规格
            //this.goodsFormulaSpecificationsList = response.data.data.list;

            if(response.data.data.list.length>0){
              this.packageGoodsForm.specifications = response.data.data.list.map(item => ({
                specification: item.specificationsName,
                packageGoodsAmountOptions:[{amountFluctuate:'增加',amountFluctuateValue:1}, {amountFluctuate:'减少',amountFluctuateValue:0}],
                selectedAmountFluctuate: 1, amount: 0.00,isDefault:false,
              }));
              //进入打开第一个
              this.packageGoodsSpecificationRadio = this.packageGoodsForm.specifications[0].specification
              //默认选中第一个
              this.selectedSpecification = this.packageGoodsForm.specifications[0].specification
            }else {
              //如果没有配方 使用商品本身的规格
              detailGoods(this.packageGoodsForm.goodsId).then((response) => {
                const specifications = response.data.data.specifications.map(item => ({
                  specification: item.specification,
                  packageGoodsAmountOptions:[{amountFluctuate:'增加',amountFluctuateValue:1}, {amountFluctuate:'减少',amountFluctuateValue:0}],
                  selectedAmountFluctuate: 1, amount: 0.00,isDefault:false,
                }));

                this.$nextTick(()=>{
                  this.packageGoodsForm.specifications = specifications;
                })
                //进入打开第一个
                this.packageGoodsSpecificationRadio = specifications[0].specification
                //默认选中第一个
                this.selectedSpecification = specifications[0].specification
              });
            }
          })*/

    },
    //添加套餐类目
    submitPackageCategoryForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //创建套餐类目
          addPackageCategory(this.packageCategoryForm).then((res) => {
            this.$notify({
              title: "成功",
              message: "添加套餐类目成功",
              type: "success",
            });
            this.resetPackageCategoryForm(formName);
            //关闭弹窗
            this.dialogVisibleForPackageCategory = false
            this.handlerListPackageCategory(this.packageCategoryForm.packageId);

          })
            .catch((res) => {});
        }
      });
    },
    //重置新建弹出框
    resetPackageCategoryForm(formName){
      this.$refs[formName].resetFields();
    },
    //类目列表
    handlerListPackageCategory(packageId){
      listPackageCategory({packageId:packageId}).then((res) => {
        this.packageCategoryList = res.data.data
        if(this.packageCategoryList.length>0){
            this.packageCategoryId = this.packageCategoryList[this.packageCategoryList.length-1].id

            //存在类目 就获取下列商品 套餐商品列表查询
          goodsListPackageCategory({packageId:packageId,packageCategoryId: this.packageCategoryId}).then((res) => {
            this.packageGoodsList = res.data.data;
            this.listPackageGoodsLoading = false;
          })
        }
      })
    },
    handlePackageCategoryRemove(packageCategory){
      deletePackageCategory(packageCategory.id).then((res) => {
        this.$notify({
          title: "成功",
          message: "删除套餐类目成功",
          type: "success",
        });
        this.handlerListPackageCategory(packageCategory.packageId);
      })
    },
    //保留两位小数
    formatToTwoDecimalPlaces(inputValue) {
      if (inputValue) {
        this.packageGoodsForm.amount = parseFloat(inputValue).toFixed(2);
      }
    }

  },
};
</script>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.avatar-uploader__status_label {
  display: block;
  color: red;
}

.inline,
.inline input {
  display: inline;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0; /* 可以根据需要调整 */
}

.dialog-footer .el-button {
  margin-left: 10px; /* 间隔 */
}

</style>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
